<?php
/**
 * 视频裁剪接口
 */
require_once dirname(__DIR__)."/login_filter.php";
use app\cls\tom\FFmpeg;
use app\cls\tom\Response;
use app\cls\tom\Config;

//接收参数
$video_url=$_REQUEST['video_url'];
$start=$_REQUEST['start'];
$end=$_REQUEST['end'];
if(empty($video_url) || empty($start) || empty($end)){
    Response::output(-1,"参数错误");
}
$ffmpeg = new FFmpeg();
//获取视频时长
$video_time=$ffmpeg->getVideoLen($video_url);
//var_dump($video_time);
//var_dump($end);exit;
if($video_time < $end){
    Response::output(-1,"视频结束时间不能大于视频总时长");
}
//格式化开始时间
$res_start=$ffmpeg->formatFFmpegTime($start);
//格式化结束时间
$res_end=$ffmpeg->formatFFmpegTime($end);

//获取临时存储目录
$tmp_dir=tmp_dir();
$status[0]['start']=$res_start;
$status[0]['duration']=$res_end;
$cut_video_url=$ffmpeg->cutVideo($video_url,$tmp_dir,$status);
//var_dump($cut_video_url);exit;
//判断是否裁剪成功
if($cut_video_url){
    //合并视频重新存储的路径
    $upload_dir=upload_dir("tmp",pathinfo($video_url,PATHINFO_EXTENSION));
    //合并视频
    $ok=$ffmpeg->mergeTVideo($cut_video_url,$upload_dir['uploadpath'],false);
    //判断是否合并成功
    if($ok){
        $data['video_url']=$upload_dir['savehttp'];
        $data['status']="ok";
        Response::output(0,"裁剪成功",$data);
    }else{
        Response::output(-1,"合并视频失败");
    }
}else{
    Response::output(-1,"裁剪失败");
}
//$res=upload_dir("video",pathinfo($video_url,PATHINFO_EXTENSION));
//var_dump($res);





//获取临时目录
function tmp_dir($type="tmp"){
    //解决跨域问题
    $allUploadConfig = Config::load("cos_upload");
    //创建上传目录，配置上传
    $date1=date("Y",time());
    $date2=date("m",time());
    $date3=date("d",time());
    $dir="/".$date1."/".$date2."/".$date3;
    $uploadpath1=$allUploadConfig[$type]['savepath'];
    //这是服务器上的上传地址
    $uploadpath=$uploadpath1.$dir;
    //不存在目录就创建
    if(!file_exists($uploadpath)){
        mkdir($uploadpath,0777,true);
    }
    return $uploadpath;
}

/**
 * 返回上传地址
 */
function upload_dir($type="tmp",$suffix="mp4"){
    //解决跨域问题
    $allUploadConfig = Config::load("cos_upload");
    //创建上传目录，配置上传
    $date1=date("Y",time());
    $date2=date("m",time());
    $date3=date("d",time());
    $dir="/".$date1."/".$date2."/".$date3;
    $uploadpath1=$allUploadConfig[$type]['savepath'];
    $uploadpath2=$allUploadConfig[$type]['savehttp'];
    $key1=rand(1000,10000);
    $key2=rand(10000,20000);
    $key3=rand();
    $file_name=$key1.$key2.$key3;
    //这是服务器上的上传地址
    $uploadpath['uploadpath']=$uploadpath1.$dir."/".$file_name.".{$suffix}";
    if($type=="tmp"){
        mkdir($uploadpath1.$dir."/".$file_name,0777,true);
    }
    //这是网络访问地址
    $uploadpath['savehttp']=$uploadpath2.$dir."/".$file_name.".{$suffix}";
    return $uploadpath;
}